package com.thirteenClassicsServer.cacheService;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thirteenClassics.async.ThreadPoolManager;
import com.thirteenClassics.entity.Book;
import com.thirteenClassicsServer.mapper.BookMapper;
import com.thirteenClassicsServer.mapper.CatalogBookMapper;
import com.thirteenClassicsServer.mapper.PictureMapper;
import com.thirteenClassicsServer.mapper.SentenceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;

@Service
public class BookServiceCache {
    @Resource
    private BookMapper bookMapper;
    @Resource
    private CatalogBookMapper catalogBookMapper;
    @Resource
    private SentenceMapper sentenceMapper;
    @Resource
    private PictureMapper pictureMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;


    public Book selectBookById(Long bookId) {
        String bookCacheKey = "book:bookId:" + bookId;
        String bookJson = redisTemplate.opsForValue().get(bookCacheKey);
        if (bookJson != null) {
            try {
                return objectMapper.readValue(bookJson, Book.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 如果 book 缓存没有数据，则从数据库中查询
        Book book = bookMapper.selectbookById(bookId);
        if (book != null) {
            cacheBookObject(book);
        }
        return book;
    }

    public Book selectMinorityBookByEntryId(Long entryId) {
        // 构建 entryId - bookId 映射缓存键
        String entryIdCacheKey = "entryId:bookId:" + entryId;

        // 从缓存中读取 bookId
        String bookId = redisTemplate.opsForValue().get(entryIdCacheKey);
        if (bookId == null) {
            // 如果缓存中没有数据，则从数据库中查询
            Book book = bookMapper.selectMinorityBookByEntryId(entryId);
            if (book != null) {
                bookId = String.valueOf(book.getId());
                redisTemplate.opsForValue().set(entryIdCacheKey, bookId, Duration.ofDays(7));
                cacheBookObject(book);
            } else {
                return null;
            }
        }

        // 使用 bookId 获取 book 对象
        String bookCacheKey = "book:bookId:" + bookId;
        String bookJson = redisTemplate.opsForValue().get(bookCacheKey);
        if (bookJson != null) {
            try {
                return objectMapper.readValue(bookJson, Book.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 如果 book 缓存没有数据，则从数据库中查询
        Book book = bookMapper.selectbookById(Long.parseLong(bookId));
        if (book != null) {
            cacheBookObject(book);
        }
        return book;
    }

    private void cacheBookObject(Book book) {
        try {
            String bookCacheKey = "book:bookId:" + book.getId();
            redisTemplate.opsForValue().set(bookCacheKey, objectMapper.writeValueAsString(book), Duration.ofDays(7));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateEntryTimeAndNameAsync(Long bookId, String userName) {
        ThreadPoolManager.getExecutorService().submit(() -> {
            LocalDateTime now = LocalDateTime.now();
            // 更新数据库
            bookMapper.updateEntryTimeAndName(bookId, now, userName);

            // 从数据库中查询更新后的Book对象
            Book updatedBook = bookMapper.selectbookById(bookId);
            if (updatedBook != null) {
                try {
                    String cacheKey = "book:bookId:" + bookId;
                    redisTemplate.opsForValue().set(cacheKey, objectMapper.writeValueAsString(updatedBook), Duration.ofDays(7));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
